/**
 * 
 */
package com.weiaibenpao.demo.chislim.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Point;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Settings;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.weiaibenpao.demo.chislim.MyApplication;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;


public class Utils {

	/**
	 * 得到屏幕宽度
	 */
	public static int getScreenWidth() {
		Context context = MyApplication.getInstance();
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		int screenWidth = size.x;
		return screenWidth;
	}

	/**
	 * 得到屏幕高度
	 */
	public static int getScreenHeight() {
		Context context = MyApplication.getInstance();
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		int screenHeight = size.y;
		return screenHeight;
	}
	/**
	 * dp--->px
	 *
	 * @param dp
	 * @return
	 */
	public static  int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				Resources.getSystem().getDisplayMetrics());
	}

	/**
	 * sp--->px
	 *
	 * @param sp
	 * @return
	 */
	public static int sp2px(int sp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
				Resources.getSystem().getDisplayMetrics());
	}

	/**
	 * 保留两位小数
	 * @param num
	 * @return
	 */
	public static String decimalFormat(Object num){
		DecimalFormat decimalFormat = new DecimalFormat("0.00");
		return decimalFormat.format(num);
	}
	public static String  getFormattedTime(long time,String format) {
		Date date = new Date(time);
		SimpleDateFormat dateFormat = new SimpleDateFormat(format,Locale.CHINA);
		return dateFormat.format(date);
	}

	//形如“2015-08-31 21:08:06”等格式化string类型转换成long类型
	public static long dateStrToLong(String dateStr,String format){
		SimpleDateFormat dateFormat = new SimpleDateFormat(format,Locale.CHINA);
		long result = 0;
		try {
			Date date = dateFormat.parse(dateStr);
			result = date.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return result;
	}


	public static void showSoftInput(Context context){
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		//imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
	}

	public static void hideSoftInput(Context context, View view){
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
	}

	public static boolean isShowSoftInput(Context context){
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		//获取状态信息
		return imm.isActive();//true 打开
	}


	/**
	 * 检测网络是否可用
	 *
	 * @return
	 */
	public static boolean isNetWorkConnected() {
		Context context = MyApplication.getInstance();
		ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if (mNetworkInfo != null) {
			return mNetworkInfo.isAvailable();
		}
		return false;
	}

	// 检测服务是否正在运行
	public static boolean isServiceRunning( String serviceName) {
		ActivityManager manager = (ActivityManager) MyApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
		for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
			if (serviceName.equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	public static SpannableStringBuilder getBoldColorStr(String originalStr, int colorEnd, int spanColor) {
		SpannableStringBuilder spannableString = new SpannableStringBuilder(originalStr);
		spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, colorEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//		spannableString.setSpan(new ForegroundColorSpan(spanColor), 0, colorEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		return spannableString;
	}

	public static SpannableStringBuilder getDoubleBoldColorStr(String originalStr,int firstStart,int firstEnd,int secondStart, int secondEnd, int spanColorr) {
		SpannableStringBuilder spannableString = new SpannableStringBuilder(originalStr);
		spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), firstStart, firstEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), secondStart, secondEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//		spannableString.setSpan(new ForegroundColorSpan(spanColorr), firstStart, firstEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//		spannableString.setSpan(new ForegroundColorSpan(spanColorr), secondStart, secondEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		return spannableString;
	}

	public static String getHmsTime(int time) {
		String timeStr;
		int hour;
		int minute;
		int second;
		if (time <= 0)
            return "00:00:00";
		else {
			minute = time / 60;
			if (minute < 60) {
				second = time % 60;
				timeStr = "00:" + unitFormat(minute) + ":" + unitFormat(second);
			} else {
				hour = minute / 60;
				if (hour > 99)
					return "99:59:59";
				minute = minute % 60;
				second = time - hour * 3600 - minute * 60;
				timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
			}
		}
		return timeStr;
	}

	private static String unitFormat(int i) {
		String retStr;
		if (i >= 0 && i < 10)
			retStr = "0" + Integer.toString(i);
		else
			retStr = "" + i;
		return retStr;
	}


	/**
	 * 判断应用是否处于前台
	 * @param packageName
	 * @return
	 */
	public static boolean isAppForeground(String packageName)
	{
		ActivityManager activityManager = (ActivityManager) MyApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> processInfos = activityManager.getRunningAppProcesses();
		if(processInfos.size() == 0) {
			return false;
		}
		for(ActivityManager.RunningAppProcessInfo process:processInfos)
		{
//			Log.d("isAppForeground",Integer.toString(process.importance));
//			Log.d("isAppForeground",process.processName);
			if(process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
					process.processName.equals(packageName))
			{
				return true;
			}
		}
		return false;
	}


	/**
	 * 判断某个Activity是否在前台
    */
	public static boolean isActivityForeground(String className) {
		if (TextUtils.isEmpty(className)) {
			return false;
		}
		ActivityManager am = (ActivityManager) MyApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
		if (list != null && list.size() > 0) {
			ComponentName cpn = list.get(0).topActivity;
			if (className.equals(cpn.getClassName())) {
				return true;
			}
		}
		return false;
	}


	public static String getSHA1(Context context) {
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					context.getPackageName(), PackageManager.GET_SIGNATURES);
			byte[] cert = info.signatures[0].toByteArray();
			MessageDigest md = MessageDigest.getInstance("SHA1");
			byte[] publicKey = md.digest(cert);
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < publicKey.length; i++) {
				String appendString = Integer.toHexString(0xFF & publicKey[i])
						.toUpperCase(Locale.US);
				if (appendString.length() == 1)
					hexString.append("0");
				hexString.append(appendString);
			}
			return hexString.toString();
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
	 * @param context
	 * @return true 表示开启
	 */
	public static  boolean isGPSEnabled(final Context context) {
		LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		// 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
		boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		// 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
		boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//		if (isGpsEnabled || network) {
//			return true;
//		}
		return isGpsEnabled;
	}

	/**
	 * 强制帮用户打开GPS
	 * @param context
	 */
	public static  void enableGPS(Context context) {
//		Intent GPSIntent = new Intent();
//		GPSIntent.setClassName("com.android.settings",
//				"com.android.settings.widget.SettingsAppWidgetProvider");
//		GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
//		GPSIntent.setData(Uri.parse("custom:3"));
//		try {
//			PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
//			Log.e("openGps","openGps");
//		} catch (PendingIntent.CanceledException e) {
//			e.printStackTrace();
//		}

		Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		context.startActivity(intent);
	}

	public static void setAudioVolume(float ratio){
		AudioManager audioManager  = (AudioManager) MyApplication.getInstance().getSystemService(Context.AUDIO_SERVICE);
		if(audioManager != null) {
			int volume =(int) (audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)*ratio);
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
		}
	}

	public static void setMinimumAudioVolume(float minimumRatio){
		AudioManager audioManager  = (AudioManager) MyApplication.getInstance().getSystemService(Context.AUDIO_SERVICE);
		if(audioManager != null) {
			int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
			int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
			int minimumVolume = (int) (maxVolume * minimumRatio);
			Log.e("setMinimumAudioVolume","minimumAudioVolume "+minimumVolume+"\n maxVolume "+maxVolume+"current volume "+currentVolume);
			if(currentVolume < minimumVolume){
				audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,minimumVolume,0);
				Log.e("setMinimumAudioVolume","当前音量小于最低音量");
			}
		}
	}


	public static String getProcessName(Context context) {
		int pid = android.os.Process.myPid();
		ActivityManager mActivityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
				.getRunningAppProcesses()) {
			if (appProcess.pid == pid) {
				return appProcess.processName;
			}
		}
		return "";
	}

	/**
	 * 跳转到应用设置界面
	 */
	public static void goToAppSettings(Context context) {
		Intent intent = new Intent();
		intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		intent.setData(Uri.fromParts("package", context.getPackageName(), null));
		context.startActivity(intent);
	}

	/**
	 * 判断手机格式是否正确
	 * @param mobiles
	 * @return
	 * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
	 * 联通：130、131、132、152、155、156、185、186
	 * 电信：133、153、180、189、（1349卫通）
	 * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
	 */
	public static boolean isMobileNO(String mobiles) {
		//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
		String telRegex = "[1][34578]\\d{9}" ;
		if (TextUtils.isEmpty(mobiles)) return false ;
		else return mobiles.matches( telRegex ) ;
	}
}
